﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Windows.Forms;

namespace AtlasLogInfo
{

    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            FolderBrowserDialog openFolderDialog1 = new FolderBrowserDialog();
            openFolderDialog1.ShowDialog();
            string folderPath = openFolderDialog1.SelectedPath;
            //OpenFileDialog openFileDialog1 = new OpenFileDialog();
            CurrentOperation currentOperation = new CurrentOperation();
            int connectionsToDatabase = 0;
            int atlasSessions = 0;
            int proccessedRows = 0;
            //string exit = "N";
            string currentMessageCell;
            bool integrationInProgress = false;
            bool versionsDontMatch = false;
            TimeSpan threeMinutes = new TimeSpan(0, 3, 0);
            TimeSpan fiveMinutes = new TimeSpan(0, 5, 0);
            TimeSpan fifteenMinutes = new TimeSpan(0, 15, 0);
            DateTime lastAttemptToIntegrate = new DateTime();
            DateTime timestamp = new DateTime();
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            int integrationCouner = 0;
            TimeSpan timeForIntegration = new TimeSpan();
            DateTime integrationStart = new DateTime();
            timeForIntegration = TimeSpan.MinValue;
            TimeSpan sumTimeForIntegration = new TimeSpan();
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            int versionsDontMatchCounter = 0;
            TimeSpan timeForVersionsDontMatch = new TimeSpan();
            DateTime versionsDontMatchStart = new DateTime();
            timeForVersionsDontMatch = TimeSpan.MinValue;
            TimeSpan sumTimeForVersionsDontMatch = new TimeSpan();
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            int dataRequestCounter = 0;
            TimeSpan timeForDataRequest = new TimeSpan();
            DateTime dataRequestStart = new DateTime();
            timeForDataRequest = TimeSpan.MinValue;
            TimeSpan sumTimeForDataRequest = new TimeSpan();
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            {
                Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
                int logsInFolder = ListOfXlsInFolder(folderPath).Count;
                for (int logsProcessed=0; logsProcessed < logsInFolder; logsProcessed++)
                {
                    //openFileDialog1.ShowDialog();
                    //Console.Clear();
                    //Console.WriteLine("Загрузка файла...");
                    //string path = openFileDialog1.FileName;

                    //Console.WriteLine("File opened: {0}", openFileDialog1.FileName);
                    Console.CursorVisible = false;
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine("Processing {0}/{1} logs", logsProcessed+1, logsInFolder);
                    Console.WriteLine("Rows processed:");
                    Console.WriteLine("File opened: {0}", ListOfXlsInFolder(folderPath)[logsProcessed]);
                    Console.WriteLine();
                    Console.SetCursorPosition(0, 4);
                    Console.WriteLine("Atlas sessions:");
                    Console.SetCursorPosition(0, 5);
                    Console.WriteLine("Connections to database:");
                    Console.SetCursorPosition(0, 6);
                    Console.WriteLine("Integrations:");
                    Console.SetCursorPosition(0, 7);
                    Console.WriteLine("\"Please upgrade your software...\" errors:");
                    Console.SetCursorPosition(0, 8);
                    Console.WriteLine("Data Request:");

                    string path = ListOfXlsInFolder(folderPath)[logsProcessed];
                    Microsoft.Office.Interop.Excel.Workbook ObjWorkBook = ObjExcel.Workbooks.Open
                    (path, 0, true,1, "","",false,Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,"",true,false,0,true,false,false);
                    Microsoft.Office.Interop.Excel.Worksheet WorkSheet;
                    WorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1];
                    int lastCell = ObjWorkBook.Sheets[1].Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;

                    for (int i = 1; i <= lastCell; i++)
                    {
                        if (WorkSheet.Cells[i, "E"].Value != null)
                        {
                            currentMessageCell = WorkSheet.Cells[i, "E"].Value.ToString();
                            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            if (currentMessageCell.Contains("Number of screen devices associated is"))
                            {
                                atlasSessions++;
                                Console.SetCursorPosition(16,4);
                                Console.Write("\t\t\t{0}", atlasSessions);
                                versionsDontMatch = false;
                                integrationInProgress = false;
                                currentOperation = CurrentOperation.NoOperation;
                            }
                            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            else if (currentMessageCell == "Successfully loaded cached workspace information.")
                            {
                                connectionsToDatabase++;
                                Console.SetCursorPosition(25, 5);
                                Console.Write("\t\t\t{0}", connectionsToDatabase);
                                integrationInProgress = false;
                                versionsDontMatch = false;
                            }
                            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            else if (currentMessageCell.Contains("is greater than the maximum required version") && versionsDontMatch == false)
                            {
                                timestamp = Convert.ToDateTime(WorkSheet.Cells[i, "A"].Value);
                                versionsDontMatchStart = timestamp;
                                Console.SetCursorPosition(43, 7);
                                Console.Write("\t{0}", versionsDontMatchCounter);
                                Console.Write("\t{0}", sumTimeForVersionsDontMatch);
                                versionsDontMatch = true;
                                versionsDontMatchCounter++;
                                currentOperation = CurrentOperation.NoOperation;
                            }
                            else if (currentMessageCell.Contains("is greater than the maximum required version") && versionsDontMatch == true)
                            {
                                timestamp = Convert.ToDateTime(WorkSheet.Cells[i, "A"].Value);
                                lastAttemptToIntegrate = timestamp;
                                versionsDontMatchCounter++;
                                Console.SetCursorPosition(43, 7);
                                Console.Write("\t{0}", versionsDontMatchCounter);
                                Console.Write("\t{0}", sumTimeForVersionsDontMatch);
                                currentOperation = CurrentOperation.NoOperation;
                            }
                            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            else if (currentMessageCell.Contains("Calling J2EEIntegrate EJB to acquire a lock") && integrationInProgress == false)
                            {
                                timestamp = Convert.ToDateTime(WorkSheet.Cells[i, "A"].Value);
                                integrationStart = timestamp;
                                integrationInProgress = true;
                                if (versionsDontMatch == true)
                                {
                                    if ((timestamp - lastAttemptToIntegrate) < fifteenMinutes)
                                        sumTimeForVersionsDontMatch += (timestamp - versionsDontMatchStart);
                                    else sumTimeForVersionsDontMatch += (lastAttemptToIntegrate - versionsDontMatchStart);
                                    versionsDontMatch = false;
                                }
                                Console.SetCursorPosition(43, 7);
                                Console.Write("\t{0}", versionsDontMatchCounter);
                                Console.Write("\t{0}", sumTimeForVersionsDontMatch);
                                currentOperation = CurrentOperation.Integration;
                            }
                            else if (currentMessageCell.Contains("Successfully integrated EEU_BW_1701 workspace"))
                            {
                                if (currentOperation == CurrentOperation.Integration)
                                {
                                    timestamp = Convert.ToDateTime(WorkSheet.Cells[i, "A"].Value);
                                    timeForIntegration = (timestamp - integrationStart);
                                    sumTimeForIntegration += timeForIntegration;
                                    integrationInProgress = false;
                                    currentOperation = CurrentOperation.NoOperation;
                                    integrationCouner++;
                                    Console.SetCursorPosition(14, 6);
                                    Console.Write("\t\t\t{0}", integrationCouner);
                                    Console.Write("\t\t\t{0}", sumTimeForIntegration);
                                }

                            }
                            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            else if (currentMessageCell == "Data Request task starting")
                            {
                                timestamp = Convert.ToDateTime(WorkSheet.Cells[i, "A"].Value);
                                dataRequestStart = timestamp;
                                currentOperation = CurrentOperation.DataRequest;
                            }
                            else if (currentMessageCell == "Data Request task completed")
                            {
                                if (currentOperation == CurrentOperation.DataRequest)
                                {
                                    timestamp = Convert.ToDateTime(WorkSheet.Cells[i, "A"].Value);
                                    timeForDataRequest = (timestamp - dataRequestStart);
                                    sumTimeForDataRequest += timeForDataRequest;
                                    dataRequestCounter++;
                                    Console.SetCursorPosition(14, 8);
                                    Console.Write("\t\t\t{0}", dataRequestCounter);
                                    Console.Write("\t\t\t{0}", sumTimeForDataRequest);
                                    currentOperation = CurrentOperation.NoOperation;
                                }
                            }
                            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            proccessedRows++;
                            Console.SetCursorPosition(16, 1);
                            Console.Write("\t{0}", proccessedRows);
                        }
                    }
                    ObjExcel.Quit();
                    //Console.WriteLine("Обработать ещё один файл? Y/N");
                    //exit = Console.ReadLine().ToUpper();
                }
                Console.WriteLine("Нажмите любую клопку для выхода");
                Console.ReadKey();
            }
        }


        static List<string> ListOfXlsInFolder(string path)
        {
            List<string> xlsList = new List<string>();
            string[] filesInDir1 = Directory.GetFiles(path);
            List<string> filesInDir = new List<string>();
            int indexOfHyphen = 0;
            char[] fileCreationTime;
            char[] tempCharArr;
            for (int i = 0; i < filesInDir1.Length; i++)
            {
                if(filesInDir1[i].Contains(".xls")&& (!(filesInDir1[i].Contains(".xls.lck"))))
                filesInDir.Add(filesInDir1[i]);
            }
            filesInDir.Sort();

            //foreach (var file in filesInDir)
            //{
            //    indexOfHyphen = file.LastIndexOf('-');
            //    fileCreationTime = file.CopyTo(indexOfHyphen - 15, tempCharArr, 0, 17);

            //    if (file.IndexOf('-')
            //}

            //foreach (var item in filesInDir)
            //{
            //    Console.WriteLine(item);
            //}
            //Console.ReadKey();

            return filesInDir;
        }
    }
}


